#!/bin/sh

ACTION=$1

usage() {
    echo "Usage: $0 [--ultra-fast | --very-fast | --help]"
    echo "  --ultra-fast      Record 30fps with the fastest encoding settings (Recommended)"
    echo "  --very-fast       Record 30fps with very-fast encoding settings"
    echo "  --high-quality    Record with 60fps high quality settings (Hurt that ARM CPU!)"
    echo "  -h, --help        Show this help message"
}

record_ultra_fast() {
    wf-recorder -a$PULSEAUDIO_MONITOR -c libx264 -p crf=30 preset=ultrafast -C aac -r 30 -o $DISPLAY -f ${OUTPUT}
    echo "Recording to: ${OUTPUT}"
}

record_very_fast() {
    wf-recorder -a$PULSEAUDIO_MONITOR -c libx264 -p crf=28 preset=veryfast -C aac -r 30 -o $DISPLAY -f ${OUTPUT}
    echo "Recording to: ${OUTPUT}"
}

record_high_quality() {
    wf-recorder -a$PULSEAUDIO_MONITOR -c libx264 -p crf=23 preset=fast -C aac -r 60 -o $DISPLAY -f ${OUTPUT}
    echo "Recording to: ${OUTPUT}"
}

DISPLAY=$(batocera-resolution currentOutput)
TIMESTAMP=$(date +%Y.%m.%d-%Hh%M.%S)
OUTPUT="/userdata/recordings/capture-${TIMESTAMP}.mkv"
PULSEAUDIO_MONITOR=$(LC_ALL=C pactl info | grep -E '^Default Sink: ' | sed -e s+"^Default Sink: "+""+ | head -1).monitor

mkdir -p /userdata/recordings || exit 1

echo
echo "Recording to file: ${OUTPUT}"
echo
echo "+-------------------------------+" >&2
echo "| Press Ctrl+c to end recording |" >&2
echo "+-------------------------------+" >&2

case "$ACTION" in
    --ultra-fast)
        record_ultra_fast
        ;;
    --very-fast)
        record_very_fast
        ;;
    --high-quality)
        record_high_quality
        ;;
    -h|--help)
        usage
        exit 0
        ;;
    *)
        usage
        exit 1
        ;;
esac
